package com.wisdudu.blank.data.source.remote.client.retrofit.subscribers;


import android.text.TextUtils;

import com.wisdudu.blank.data.Injection;
import com.wisdudu.blank.data.bean.UserInfo;
import com.wisdudu.frame.support.util.MD5Util;

import org.json.JSONObject;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by qyf on 2016/3/28.
 */
public class MapSort {
    static String str = null;

    public static Map<String, Object> sortMapByKey(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, Object> sortMap = new TreeMap<>(new MapKeyComparator());
        sortMap.putAll(map);
        return sortMap;
    }

    public static String getLoginMD5PostMap(Map<String, Object> map) {
        map.put("temptime", System.currentTimeMillis() / 1000);
        map = sortMapByKey(map);
        str = "";
        for (String key : map.keySet()) {
            str += map.get(key);
        }
        map.put("sign", MD5Util.getMD5(str));
        return new JSONObject(map).toString();
    }

    public static String getMD5GetResult(Map<String, Object> map) {
        map.put("temptime", System.currentTimeMillis() / 1000);
        addMap(map);
        map = sortMapByKey(map);
        str = "";
        for (String key : map.keySet()) {
            str += map.get(key);
        }
        map.put("sign", MD5Util.getMD5(str));
        return new JSONObject(map).toString();
    }


    public static String getMD5PostResultMap(Map<String, Object> map) {
        map.put("temptime", System.currentTimeMillis() / 1000);
        addMap(map);
        map = sortMapByKey(map);
        str = "";
        for (String key : map.keySet()) {
            str += map.get(key);
        }
        map.put("sign", MD5Util.getMD5(str));
        return new JSONObject(map).toString();
    }

    private static void addMap(Map<String, Object> map) {
        if (Injection.provideUserRepo().getUserInfo() != null) {
            UserInfo userInfo = Injection.provideUserRepo().getUserInfo();
            map.put("houseid", TextUtils.isEmpty(userInfo.getHouseid()) ? "0" : userInfo.getHouseid());
            map.put("villageid", TextUtils.isEmpty(userInfo.getVillageid()) ? "0" : userInfo.getVillageid());
        }
    }

    public static class MapKeyComparator implements Comparator<String> {
        @Override
        public int compare(String str1, String str2) {
            return str1.compareTo(str2);
        }
    }
}
